<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-semibold text-gray-800">领用记录</h2>
      <button @click="$router.push('/consumable-receive/form')" class="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
        <PlusIcon class="h-5 w-5 mr-2" />
        物品领用
      </button>
    </div>

    <!-- Search Bar -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
      <form @submit.prevent="handleSearch" class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label for="itemName" class="block text-sm font-medium text-gray-700">物品名称</label>
          <input type="text" id="itemName" v-model="searchForm.itemName" placeholder="请输入物品名称" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div>
          <label for="requester" class="block text-sm font-medium text-gray-700">领用人</label>
          <input type="text" id="requester" v-model="searchForm.requester" placeholder="请输入领用人姓名" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div>
          <label for="laboratory" class="block text-sm font-medium text-gray-700">实验室</label>
          <select id="laboratory" v-model="searchForm.laboratory" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">请选择实验室</option>
            <option value="计算机实验室A">计算机实验室A</option>
            <option value="计算机实验室B">计算机实验室B</option>
            <option value="化学实验室">化学实验室</option>
            <option value="生物实验室">生物实验室</option>
            <option value="物理实验室">物理实验室</option>
          </select>
        </div>
        <div>
          <label for="receiveDate" class="block text-sm font-medium text-gray-700">领用日期</label>
          <input type="date" id="receiveDate" v-model="searchForm.receiveDate" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div class="md:col-span-4 flex justify-end space-x-3 mt-4">
          <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">搜索</button>
          <button type="button" @click="handleReset" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">重置</button>
        </div>
      </form>
    </div>

    <!-- Receive Records Table -->
    <div class="bg-white rounded-xl shadow-lg p-6">
      <div v-if="loading" class="text-center py-8">加载中...</div>
      <div v-else class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">物品名称</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">规格型号</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">领用数量</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">领用人</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">实验室</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">领用日期</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用途</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="record in receiveRecords" :key="record.id">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ record.itemName }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.specification }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.quantity }} {{ record.unit }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.requester }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.laboratory }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.receiveDate }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.purpose }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewDetail(record)" class="text-indigo-600 hover:text-indigo-900 mr-3">查看</button>
                <button @click="editRecord(record)" class="text-indigo-600 hover:text-indigo-900">编辑</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <div class="flex justify-end mt-6">
        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
          <button @click="handleCurrentChange(pagination.current - 1)" :disabled="pagination.current === 1" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
            <span class="sr-only">Previous</span>
            <ChevronLeftIcon class="h-5 w-5" aria-hidden="true" />
          </button>
          <button v-for="page in totalPages" :key="page" @click="handleCurrentChange(page)" :class="['relative inline-flex items-center px-4 py-2 border text-sm font-medium', page === pagination.current ? 'z-10 bg-indigo-50 border-indigo-500 text-indigo-600' : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50']">
            {{ page }}
          </button>
          <button @click="handleCurrentChange(pagination.current + 1)" :disabled="pagination.current === totalPages" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
            <span class="sr-only">Next</span>
            <ChevronRightIcon class="h-5 w-5" aria-hidden="true" />
          </button>
        </nav>
        <div class="ml-4 flex items-center text-sm text-gray-700">
          <span>共 {{ pagination.total }} 条</span>
          <select v-model="pagination.size" @change="handleSizeChange($event.target.value)" class="ml-2 block w-auto pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
            <option :value="10">10 条/页</option>
            <option :value="20">20 条/页</option>
            <option :value="50">50 条/页</option>
            <option :value="100">100 条/页</option>
          </select>
        </div>
      </div>

      <!-- Summary Cards -->
      <div class="grid grid-cols-1 sm:grid-cols-3 gap-6 mt-6">
        <div class="bg-gray-50 rounded-xl shadow-sm p-5 flex items-center space-x-4">
          <div class="flex-shrink-0 bg-indigo-100 p-3 rounded-full">
            <ClipboardDocumentListIcon class="h-6 w-6 text-indigo-600" />
          </div>
          <div>
            <p class="text-gray-500 text-sm">总领用次数</p>
            <p class="text-2xl font-semibold text-gray-900">{{ receiveSummary.totalReceives }}</p>
          </div>
        </div>
        <div class="bg-gray-50 rounded-xl shadow-sm p-5 flex items-center space-x-4">
          <div class="flex-shrink-0 bg-green-100 p-3 rounded-full">
            <CubeIcon class="h-6 w-6 text-green-600" />
          </div>
          <div>
            <p class="text-gray-500 text-sm">总领用数量</p>
            <p class="text-2xl font-semibold text-gray-900">{{ receiveSummary.totalQuantity }}</p>
          </div>
        </div>
        <div class="bg-gray-50 rounded-xl shadow-sm p-5 flex items-center space-x-4">
          <div class="flex-shrink-0 bg-yellow-100 p-3 rounded-full">
            <ChartBarIcon class="h-6 w-6 text-yellow-600" />
          </div>
          <div>
            <p class="text-gray-500 text-sm">本月领用</p>
            <p class="text-2xl font-semibold text-gray-900">{{ receiveSummary.monthlyReceives }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import {
  PlusIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  ClipboardDocumentListIcon,
  CubeIcon,
  ChartBarIcon,
} from '@heroicons/vue/24/outline'

const router = useRouter()

const receiveRecords = ref([])
const loading = ref(false)

const searchForm = reactive({
  itemName: '',
  requester: '',
  laboratory: '',
  receiveDate: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const receiveSummary = reactive({
  totalReceives: 0,
  totalQuantity: 0,
  monthlyReceives: 0,
})

const totalPages = computed(() => Math.ceil(pagination.total / pagination.size))

// View detail
const viewDetail = (record) => {
  showMessage('查看领用详情功能待开发', 'info')
  // router.push(`/consumable-receive/detail/${record.id}`)
}

// Edit record
const editRecord = (record) => {
  showMessage('编辑领用记录功能待开发', 'info')
  // router.push(`/consumable-receive/form/${record.id}`)
}

// Search
const handleSearch = () => {
  pagination.current = 1
  loadReceiveRecords()
}

// Reset search
const handleReset = () => {
  Object.assign(searchForm, {
    itemName: '',
    requester: '',
    laboratory: '',
    receiveDate: ''
  })
  pagination.current = 1
  loadReceiveRecords()
}

// Page size change
const handleSizeChange = (size) => {
  pagination.size = parseInt(size)
  pagination.current = 1
  loadReceiveRecords()
}

// Current page change
const handleCurrentChange = (current) => {
  if (current < 1 || current > totalPages.value) return
  pagination.current = current
  loadReceiveRecords()
}

// Load receive records
const loadReceiveRecords = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }

    const response = await request.get('/consumable-receives/list', { params })
    receiveRecords.value = response.data.records.map(record => ({
      id: record.id,
      itemName: record.itemName,
      specification: record.specification,
      quantity: record.quantity,
      unit: record.unit,
      requester: record.receiverName,
      laboratory: record.laboratoryName,
      receiveDate: record.receiveDate,
      purpose: record.purpose
    }))
    pagination.total = response.data.total

    // Calculate summary
    receiveSummary.totalReceives = response.data.total
    receiveSummary.totalQuantity = response.data.records.reduce((sum, record) => sum + record.quantity, 0)
    receiveSummary.monthlyReceives = response.data.records.filter(record => {
      const recordDate = new Date(record.receiveDate)
      const currentDate = new Date()
      return recordDate.getMonth() === currentDate.getMonth() && recordDate.getFullYear() === currentDate.getFullYear()
    }).length

  } catch (error) {
    console.error('加载领用记录失败:', error)
    showMessage('加载领用记录失败', 'error')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadReceiveRecords()
})

// Simple message display function (can be moved to a global utility)
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}
</script>
